package com.though.utils.encrypt;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import sun.misc.BASE64Decoder;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.*;

/**
 * Created with IntelliJ IDEA.
 * User: Czh
 * Date: 2018/2/7
 * Time: 上午10:53
 */
public class AesUtil {
    public static boolean initialized = false;

//    public static void main(String[] args) {
//        try {
//
//            String userInfo = AesUtil
//                    .decrypt(
//                            "Qxn7m5rFR3eBdGnw0g7VTYOZSscXvZujtseVmYcgwYvJUtewa8JZ4jbsXK2XhIfnrPC9sk2d/veqM12lo/bF4RgWccKxpfOaDFwukyuCkU9Rj+podpVluOadwFnA8NewgREBHWSu/4VQW8Vr6H5QASeBm+ft+Fw9AOSkayCmg2iiF/5YOfDb8TUr+29m3Vpq+lUniQQIKvH4mKGjS2siiHNQSTxBpFthJOlaYkv7ixHyvyONLgBqAWHGzn0sKx/DSmUo/FD+KgrQIO+nMfvaQI3xiIz5llNq9/zFhL1+DxHxUOSDlN7Tjdl5eKwZr2Yy1DxQZW6QmifoLul2Ah9MYs7nCA4Xr1kUCdvIQbDcvTtrmTp17lHhquvvr2UuqeQnk/g8xaDMrLv0bh0mGzuKY2VnfAGAlPNyCzT3toZV0IitAJ5R18BAHNmHW8/SKcLlVHC+6kVcFIwT5oUF+Rf+2A==",
//                            "rH5lOklzG6xbf5hlMwXUow==",
//                            "NSnaTP5TTT9/bMNI3N/DIQ==");
//            System.out.println(userInfo);
//
//        } catch (InvalidAlgorithmParameterException e) {
//            e.printStackTrace();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    /**
     * AES解密
     *
     * @return
     * @throws InvalidAlgorithmParameterException
     * @throws NoSuchProviderException
     */
    public static String decrypt(String encryptedData, String sessionKey, String iv)
            throws InvalidAlgorithmParameterException {
        initialize();
        try {
            BASE64Decoder base64Decoder = new BASE64Decoder();
            byte[] keyByte = base64Decoder.decodeBuffer(sessionKey);
            byte[] ivByte = base64Decoder.decodeBuffer(iv);
            byte[] content = base64Decoder.decodeBuffer(encryptedData);
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
            Key sKeySpec = new SecretKeySpec(keyByte, "AES");
            cipher.init(Cipher.DECRYPT_MODE, sKeySpec, generateIV(ivByte));// 初始化
            byte[] resultByte = cipher.doFinal(content);
            return new String(resultByte,"UTF-8");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    public static void initialize() {
        if (initialized)
            return;
        Security.addProvider(new BouncyCastleProvider());
        initialized = true;
    }

    // 生成iv
    public static AlgorithmParameters generateIV(byte[] iv) throws Exception {
        AlgorithmParameters params = AlgorithmParameters.getInstance("AES");
        params.init(new IvParameterSpec(iv));
        return params;
    }

//    public static String AES128CBCdecrypt(String encryptedData, String sessionKey, String iv,
//                                    String appId) throws Exception {
//        // 被加密的数据
//        byte[] dataByte = Base64.decodeBase64(encryptedData);
//        // 加密秘钥
//        byte[] keyByte = Base64.decodeBase64(sessionKey);
//        // 偏移量
//        byte[] ivByte = Base64.decodeBase64(iv);
//        Security.addProvider(new BouncyCastleProvider());
//        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
//        SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
//        AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
//        parameters.init(new IvParameterSpec(ivByte));
//        cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
//        byte[] resultByte = cipher.doFinal(dataByte);
//        if (null != resultByte && resultByte.length > 0) {
//            String result = new String(resultByte, "UTF-8");
//            JSONObject obj = JSONObject.fromObject(result);
//            JSONObject watermark = obj.getJSONObject("watermark");
//            if (!watermark.getString("appid").equals(appId)) {
//                throw new Exception("与小程序appid不符合");
//            }
//		/*	if (System.currentTimeMillis() - watermark.getLong("timestamp")
//					* 1000 > 10000) {
//				throw new Exception("验证时间过长");
//			}*/
//            return result;
//        }
//        return null;
//    }
}